# coding=utf-8
import os

from fastapi import FastAPI, Request

from apps.a_common.error import ER, exception_handler, exceptions, PermissionError
from apps.a_common.log import MyLogger
from apps.helloworld.views import hello_router

# 命名规则如下，蓝图加上后缀，避免发生命名冲突，所有的资源都以复数形式呈现

ROUTERS = [
	hello_router,
]

DEFAULT_APP_NAME = 'app'
DEFAULT_STATIC_DIR = 'app/static/'


def include_router(app: FastAPI):
	for router in ROUTERS:
		app.include_router(router)


def create_app(name=DEFAULT_APP_NAME, **settings_override):
	app = FastAPI(title=name)
	app.static_folder = os.path.abspath(DEFAULT_STATIC_DIR)
	init_foundations(app)
	include_router(app)
	return app


def init_foundations(app: FastAPI):
	pass

	# @app.middleware('http')
	# def before_first_request():
	# 	pass

	@app.middleware('http')
	async def handel_access_control(request: Request, call_next):
		response = await call_next(request)
		response.headers['Access-Control-Allow-Origin'] = '*'
		response.headers[
			'Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE,VIEW'
		response.headers[
			'Access-Control-Allow-Headers'] = 'Content-Type, Mall-Token, User-Token'
		return response

	@app.exception_handler(Exception)
	def errorhandler(e):
		return exception_handler(e)


#
# @app.teardown_appcontext
# def releaseDB(response):
# 	db.session.close()
# 	return response


app = create_app()
